package com.songyz.image.compress;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.songyz.image.compress.utils.CompressUtils;

@SpringBootApplication
public class Application {

    private static Logger logger = LoggerFactory.getLogger(Application.class);

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public CommandLineRunner startUp() {
        return args -> {
            String tmpdir = System.getProperty("java.io.tmpdir");

            logger.info("项目启动，清除缓存 tmpdir：{}", tmpdir);

            File file = new File(tmpdir + CompressUtils.FOLD);
            if (file.exists() && file.listFiles().length > 0) {
                Path path = Paths.get(file.getAbsolutePath());

                Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
                        Files.delete(file);
                        logger.info("删除缓存文件：{}", file);
                        return FileVisitResult.CONTINUE;
                    }

                    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                        Files.delete(dir);
                        logger.info("删除缓存文件夹：{}", dir);
                        return FileVisitResult.CONTINUE;
                    }
                });
            }
        };
    }

}
